#include <libxml/parser.h>
#include <libxml/tree.h>
// #include <libssh2.h>
#include <stdio.h>
#include <stdlib.h>


void rply_generator(const char *outfilename,struct Tunnel *tunnel){
       // 检查libxml2版本
    LIBXML_TEST_VERSION

    // 创建一个新的XML文档，并声明其版本和编码
    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
    doc->encoding = xmlStrdup(BAD_CAST "UTF-8");

    // 创建RPC元素，并为其添加xmlns属性定义命名空间
    xmlNodePtr rplyNode = xmlNewNode(NULL, BAD_CAST "rpc-reply");
    xmlSetProp(rplyNode, BAD_CAST "message-id", BAD_CAST tunnel->m_id);
    xmlSetProp(rplyNode, BAD_CAST "xmlns", BAD_CAST "urn:ietf:params:xml:ns:netconf:base:1.0");
    if(tunnel->error==0){
    xmlNodePtr opNode = xmlNewChild(rplyNode, NULL, BAD_CAST tunnel->op, NULL);
    int i=0;
    xmlNodePtr entityNode = xmlNewChild(opNode, NULL, BAD_CAST "TSNCONF", NULL);    
    for(;i<tunnel->TC_num;i++){
    xmlNodePtr nameNode = xmlNewTextChild(entityNode, NULL, BAD_CAST tunnel->TC[i].entity, BAD_CAST tunnel->TC[i].content);
    }
    i=0;
    entityNode = xmlNewChild(opNode, NULL, BAD_CAST "PortID", NULL);    
    for(;i<tunnel->PI.ci_num;i++){
    xmlNodePtr nameNode = xmlNewTextChild(entityNode, NULL, BAD_CAST "clockIdentity", BAD_CAST tunnel->PI.ci[i].clockIdentity);
    }  
    xmlNodePtr nameNode = xmlNewTextChild(entityNode, NULL, BAD_CAST "portNumber", BAD_CAST tunnel->PI.content); 
    }else{
        xmlNodePtr errorNode = xmlNewChild(rplyNode, NULL, BAD_CAST "error", NULL);
    }
    xmlAddChild((xmlNodePtr)doc, rplyNode);
    int result = xmlSaveFormatFileEnc(outfilename, doc, "UTF-8", 1);
    if (result < 0) {
        fprintf(stderr, "Error: unable to save the file %s\n", outfilename);
    }
    
    // 清理并释放内存
    xmlFreeDoc(doc);
    xmlCleanupParser();


    // FILE *file = fopen(outfilename, "r");
    // if (file == NULL) {
    //     perror("无法打开XML响应文件");
    //     return EXIT_FAILURE;
    // }
    // size_t bytes_read = fread(buffer, sizeof(char), buffer_size, file);
    // fclose(outfilename);
    // ssh_cahnnel_write(ssh_get_channel(accepted_session), buffer, sizeof(buffer));

}